//
//  DeviceEditController.m
//  YSSmartHome
//
//  Created by yanghao on 2016/9/30.
//  Copyright © 2016年 yahaong. All rights reserved.
//

#import "DeviceEditController.h"
#import "NewDeviceIconCell.h"
#import "NewDeviceView.h"
#import "MQTTCoverTool.h"
#import "MQTTSessionManager.h"
#import "RoomMenusController.h"
#import "RoomMenuAninator.h"
#import "XAIGateway.h"
#import "UIView+HUD.h"
#import "GlobalConst.h"

@interface DeviceEditController ()
<
UICollectionViewDelegate,
UICollectionViewDataSource,
UITableViewDelegate,
UITableViewDataSource

>

@property (nonatomic, strong)UILabel *m_lblFromGateway;
@property (nonatomic, strong)UILabel *gatewayLabel;
@property (nonatomic, strong)UILabel *m_lblName;
@property (nonatomic, strong)UITextField *m_textName;
@property (nonatomic, strong)UILabel *m_lblRoom;
@property (nonatomic, strong)UILabel *m_lblRoom2;
@property (nonatomic, strong)UIButton *m_btnRoomMenu;
@property (nonatomic, strong)UICollectionView *m_collectionViewIcons;
@property (nonatomic, strong)UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, strong)NSIndexPath *selectedIndex;
@property (nonatomic, strong)NSArray *datasouce;
@property (nonatomic, strong)RoomMenuAninator *roomMenuAninator;
@property (nonatomic, strong)UIImageView *m_imgSharp;
@property (nonatomic, strong)UITableView *m_tableViewMenu;
@property (nonatomic, strong)NSMutableArray *m_arrayRoom;
@property (nonatomic, strong)UIView *m_viewCover;
@end


static NSString *const  ZTNewDeviceIconCellReuseIdentifier = @"ZTNewDeviceIconCellReuseIdentifier";
@implementation DeviceEditController


#pragma mark - life cycle
- (void)dealloc
{
    debugLogInfo(@"DeviceEditController dealloc");
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initSubviews];
    NSString *roomPath = [MQTTSessionManager roomListPath];
    self.m_arrayRoom = [NSKeyedUnarchiver unarchiveObjectWithFile:roomPath];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.devListView setHidden:NO];
}


#pragma mark - event response
- (void)didtappedSaveButton
{
    if (self.m_textName.text.length == 0)
    {
        [self.view yh_showMsgHUD:@"设备名称不能为空"];
        return;
    }
    NSInteger intengerSelect = 0;
    if (self.selectedIndex != nil)
    {
        intengerSelect = self.selectedIndex.row;
    }
    NSString *nameStr = [NSString stringWithFormat:@"%@.%@.%zd",self.m_lblRoom2.text,self.m_textName.text,intengerSelect];
    self.device.name = nameStr;
    if (self.fromMe)
    {
        [self setDevName:self.device];
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    __weak typeof(self)weakSelf = self;
    if (self.setDevInfoBlcok)
    {
        __strong typeof(weakSelf) strongSelf = self;
        if (!strongSelf) {
            return ;
        }
        strongSelf.setDevInfoBlcok(self.device);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setDevName:(ZTDevice *)dev
{
    NSString *strName = [NSString stringWithFormat:@"%@",dev.name];
    XAITYPEAPSN devApsn = dev.apsn;
    XAITYPELUID devLuid = dev.luid;
    uint8_t status = 0xff;
    NSMutableArray* array  = [NSMutableArray array];
    
    XAITLV* tlv = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_BIN_APSN bytes:&devApsn length:sizeof(devApsn)];
    [array addObject:tlv];
    
    tlv = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_BIN_LUID bytes:&devLuid length:sizeof(devLuid)];
    [array addObject:tlv];
    
    tlv = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_BIN_DIGITAL_UNSIGN bytes:&status length:sizeof(status)];
    [array addObject:tlv];
    
    tlv = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_ASCII_TEXT bytes:(void*)[strName cStringUsingEncoding:NSUTF8StringEncoding] length:(int)[strName dataUsingEncoding:NSUTF8StringEncoding].length];
    [array addObject:tlv];
    
    NSError* error =  [kMQTTSessionManager.xai sendCMD:0x09 toApsn:kMQTTSessionManager.currentUser.currentBindApsn toLuid:kGATEWAYLUID datas:array];
    if (error.code == 0)
    {
        debugLogInfo(@"改名成功");
    }
    else
    {
        debugLogInfo(@"改名失败%@",error.localizedDescription);
    }
}
- (void)menu:(UIButton *)menuBtn
{
    menuBtn.selected = !menuBtn.selected ;
    if (menuBtn.selected) {
        [self poperRoomMenuViewExtendAnimation];
    } else {
        [self poperRoomMenuViewFoldAnimation];
    }
}

- (void)iconCellClick:(UITapGestureRecognizer *)tapGesture {
    
    NSIndexPath *currentIndex = [self.m_collectionViewIcons indexPathForItemAtPoint:  [tapGesture locationInView:tapGesture.view]];
    if (self.selectedIndex == currentIndex || currentIndex == nil) {
        NewDeviceIconCell *cell  = (NewDeviceIconCell *) [self.m_collectionViewIcons cellForItemAtIndexPath:self.selectedIndex];
        cell.selected = !cell.selected;
        self.selectedIndex = nil;
        return;
    }
    if (currentIndex) {
        NewDeviceIconCell *cell  = (NewDeviceIconCell *) [self.m_collectionViewIcons cellForItemAtIndexPath:self.selectedIndex];
        cell.selected = !cell.selected;
        cell = (NewDeviceIconCell *) [self.m_collectionViewIcons cellForItemAtIndexPath:currentIndex];
        cell.selected = !cell.selected;
        self.selectedIndex = currentIndex;
    }
}

- (void)close
{
    [self poperRoomMenuViewFoldAnimation];
}
- (void)setDevice:(ZTDevice *)device
{
    _device = device;
    self.m_collectionViewIcons.hidden = (device.devType !=ZTDeviceTypeOneWaySocket);
    self.m_textName.text =  [device getDeviceName];;
}


#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.datasouce.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NewDeviceIconCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ZTNewDeviceIconCellReuseIdentifier forIndexPath:indexPath];
    cell.icon = self.datasouce[indexPath.row];
    return cell;
}

#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return self.m_arrayRoom.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MenucellIdentifier"];
    cell.textLabel.text =  self.m_arrayRoom[indexPath.row];
    cell.imageView.image = [UIImage imageNamed:@"newdevice_circle"];
    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.m_lblRoom2.text = self.m_arrayRoom[indexPath.row];
    [self poperRoomMenuViewFoldAnimation];
    
}


#pragma mark - private method


- (void)initSubviews
{
    [self initNavigationView];
    [self.view addSubview:self.m_lblFromGateway];
    [self.view addSubview:self.gatewayLabel];
    [self.view addSubview:self.m_lblName];
    [self.view addSubview:self.m_textName];
    [self.view addSubview:self.m_lblRoom];
    [self.view addSubview:self.m_btnRoomMenu];
    [self.view addSubview:self.m_lblRoom2];
    [self.view addSubview:self.m_collectionViewIcons];
    [self.view addSubview:self.m_viewCover];
    [self.view addSubview:self.m_imgSharp];
    [self.view addSubview:self.m_tableViewMenu];
    [self layoutPageSubViews];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(iconCellClick:)];
    [self.m_collectionViewIcons addGestureRecognizer:tapGesture];
}
- (void)layoutPageSubViews
{
    [self.m_lblFromGateway mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.height.equalTo(35);
        make.leading.equalTo(self.view).offset(10);
    }];
    
    [self.gatewayLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.m_lblFromGateway.trailing).offset(10);
        make.centerY.equalTo(self.m_lblFromGateway);
        
    }];
    
    [self.m_lblName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view);
        make.height.equalTo(55);
        make.width.equalTo(75);
        make.top.equalTo(self.m_lblFromGateway.bottom);
    }];
    
    [self.m_textName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self.m_lblName);
        make.leading.equalTo(self.m_lblName.trailing);
        make.trailing.equalTo(self.view.trailing);
    }];
    
    
    [self.m_lblRoom mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.height.trailing.equalTo(self.m_lblName);
        make.top.equalTo(self.m_lblName.bottom).offset(10);
        
    }];
    
    [self.m_btnRoomMenu mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self.m_lblRoom);
        make.trailing.equalTo(self.view);
        make.width.equalTo(60);
    }];
    
    [self.m_lblRoom2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.height.equalTo(self.m_lblRoom);
        make.trailing.equalTo(self.m_btnRoomMenu.leading).offset(-1);
        make.leading.equalTo(self.m_lblName.trailing);
    }];
    
    [self.m_collectionViewIcons mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view).offset(10);
        make.trailing.equalTo(self.view).offset(-10);
        make.bottom.equalTo(self.view);
        make.top.equalTo(self.m_lblRoom.bottom).offset(20);
    }];
    
    [self.m_viewCover mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.m_lblRoom.bottom);
        make.leading.bottom.trailing.equalTo(self.view);
        
    }];
    
    [self.m_imgSharp mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.m_btnRoomMenu.bottom);
        make.width.equalTo(14);
        make.height.equalTo(0);
        make.centerX.equalTo(self.m_btnRoomMenu);
    }];
    
    [self.m_tableViewMenu mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.m_imgSharp.bottom);
        make.trailing.equalTo(self.view).offset(-10);
        make.height.equalTo(0);
        make.leading.equalTo(10);
    }];
    
}

- (void)initNavigationView
{
    self.navigationItem.title = @"设备编辑";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(didtappedSaveButton)];
    self.gatewayLabel.text = kMQTTSessionManager.currentGateway.name;
}
- (void)poperRoomMenuViewFoldAnimation
{
    
    [self.m_tableViewMenu mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(0);
    }];
    [UIView animateWithDuration:0.3 animations:^{
        [self.m_tableViewMenu layoutIfNeeded];
    } completion:^(BOOL finished) {
        [self.m_imgSharp mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(0);
        }];
        [UIView animateWithDuration:0.1 animations:^{
            [self.m_imgSharp layoutIfNeeded];
        } completion:^(BOOL finished) {
            self.m_viewCover.hidden = true;
        }];
    }];
}

- (void)poperRoomMenuViewExtendAnimation
{
    self.m_viewCover.hidden = NO;
    [self.m_imgSharp mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(8);
    }];
    [self.m_tableViewMenu mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(330);
    }];
    [UIView animateWithDuration:0.1 animations:^{
        [self.m_imgSharp layoutIfNeeded];
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.3 animations:^{
            [self.m_tableViewMenu layoutIfNeeded];
        } completion:^(BOOL finished) {
            
        }];
    }];
}
#pragma mark - getters and setters
- (UILabel *)m_lblFromGateway
{
    if (!_m_lblFromGateway) {
        _m_lblFromGateway = [[UILabel alloc]init];
        _m_lblFromGateway.backgroundColor = kBgColor;
        _m_lblFromGateway.text = @"归属网关";
        _m_lblFromGateway.font = [UIFont systemFontOfSize:13];
    }
    return _m_lblFromGateway;
}

- (UILabel *)gatewayLabel
{
    if (!_gatewayLabel) {
        _gatewayLabel = [[UILabel alloc]init];
        _gatewayLabel.backgroundColor = kBgColor;
        _gatewayLabel.text = @"客厅网关";
        _gatewayLabel.font = [UIFont systemFontOfSize:14];
    }
    return _gatewayLabel;
}
- (UILabel *)m_lblName {
    if (!_m_lblName) {
        _m_lblName = [[UILabel alloc]init];
        _m_lblName.text = @"名称";
        _m_lblName.textAlignment = NSTextAlignmentCenter;
        _m_lblName.backgroundColor = [UIColor whiteColor];
    }
    return _m_lblName;

}
- (UITextField *)m_textName
{
    if (!_m_textName) {
        _m_textName = [[UITextField alloc]init];
        _m_textName.placeholder = @"请输入你的设备名称";
        _m_textName.backgroundColor = [UIColor whiteColor];
    }
    return _m_textName;
}

- (UILabel *)m_lblRoom
{
    if (!_m_lblRoom) {
        _m_lblRoom = [[UILabel alloc]init];
        _m_lblRoom.text = @"房间";
        _m_lblRoom.textAlignment = NSTextAlignmentCenter;
        _m_lblRoom.backgroundColor = [UIColor whiteColor];
    }
    return _m_lblRoom;
}

- (UILabel *)m_lblRoom2
{
    if (!_m_lblRoom2) {
        _m_lblRoom2 = [[UILabel alloc]init];
        _m_lblRoom2.text = @"客厅";
        _m_lblRoom2.textAlignment = NSTextAlignmentLeft;
        _m_lblRoom2.backgroundColor = [UIColor whiteColor];
    }
    return _m_lblRoom2;
}

- (UIButton *)m_btnRoomMenu
{
    if (!_m_btnRoomMenu) {
        _m_btnRoomMenu = [[UIButton alloc]init];
        _m_btnRoomMenu.backgroundColor = [UIColor whiteColor];
        [_m_btnRoomMenu setImage:[UIImage imageNamed:@"newdevice_icon_menu"] forState:UIControlStateNormal];
        [_m_btnRoomMenu addTarget:self action:@selector(menu:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _m_btnRoomMenu;
}

- (UICollectionViewFlowLayout *)flowLayout
{
    if (!_flowLayout) {
        _flowLayout = [[UICollectionViewFlowLayout alloc]init];
        _flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        _flowLayout.itemSize = CGSizeMake((kScreenWidth - 30) /2 , (kScreenWidth - 30) /2  *0.6875);
    }
    return _flowLayout;
}

- (UICollectionView *)m_collectionViewIcons
{
    if(!_m_collectionViewIcons) {
        _m_collectionViewIcons = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:self.flowLayout];
        _m_collectionViewIcons.delegate = self;
        _m_collectionViewIcons.dataSource = self;
        _m_collectionViewIcons.backgroundColor = kBgColor;
        [_m_collectionViewIcons registerClass:[NewDeviceIconCell class] forCellWithReuseIdentifier:ZTNewDeviceIconCellReuseIdentifier];
    }
    return _m_collectionViewIcons;
}
- (NSArray *)datasouce
{
    if (!_datasouce)
    {
        _datasouce = @[@"home_socket_close_icon0",@"home_socket_close_icon1",@"home_socket_close_icon2",@"home_socket_close_icon3",@"home_socket_close_icon4",@"home_socket_close_icon5"];
    }
    return _datasouce;
}
- (RoomMenuAninator *)roomMenuAninator
{
    if (!_roomMenuAninator) {
        _roomMenuAninator = [[RoomMenuAninator alloc]init];
        _roomMenuAninator.presentFrame = CGRectMake(100, 100, 200, 350);
    }
    return _roomMenuAninator;
}

- (UIImageView *)m_imgSharp
{
    if (!_m_imgSharp) {
        _m_imgSharp = [[UIImageView alloc]init];
        _m_imgSharp.image = [UIImage imageNamed:@"newdevice_sharp"];
    }
    return _m_imgSharp;
}
- (UITableView *)m_tableViewMenu
{
    if (!_m_tableViewMenu) {
        _m_tableViewMenu = [[UITableView alloc]init];
        _m_tableViewMenu.backgroundColor = [UIColor whiteColor];
        _m_tableViewMenu.delegate = self;
        _m_tableViewMenu.dataSource = self;
        _m_tableViewMenu.showsVerticalScrollIndicator = NO;
        _m_tableViewMenu.showsHorizontalScrollIndicator= NO;
        _m_tableViewMenu.rowHeight = kIphoneSize_Height(52);
        [_m_tableViewMenu registerClass:[UITableViewCell class] forCellReuseIdentifier:@"MenucellIdentifier"];
        UIView *footerView = [[UIView alloc]init];
        _m_tableViewMenu.tableFooterView = footerView;
        _m_tableViewMenu.layer.cornerRadius = 5.0f;
        _m_tableViewMenu.layer.masksToBounds = YES;
    }
    return _m_tableViewMenu;
}


- (UIView *)m_viewCover
{
    if (!_m_viewCover) {
        _m_viewCover = [[UIView alloc]init];
        _m_viewCover.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.2];
        _m_viewCover.hidden = YES;
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(close)];
        [_m_viewCover addGestureRecognizer:tapGesture];
    }
    return _m_viewCover;
}
@end
